<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Ramsey\Uuid\Uuid;

class GoodsCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'goods:command';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Sync Goods';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //修改本地商品库
//        $this->updateDheGoods();

        //修改宝坚商品库
//        $this->syncBjGoods();

        //删除重复商品
//        $this->delRepeatGoods();

        //已删除商品还原
//        $this->resetDelGoods();

        $this->addTyGoods();
    }

    public function addTyGoods()
    {
        $list = Db::table('vms_goods') -> get();

        foreach($list as $v) {
            $data =[
                "acceptance_id" => Str::random(16),
                "sku_id"        => $v -> goods_sku,
                "bar_code"      => $v -> barcode,
                "goods_name"    => $v -> goods_name,
                "weight"        => $v -> size_name,
                "cost_price"    => $v -> price,
                "sell_price"    => $v -> price,
                "is_standard"   => $v -> is_standard,
                "is_register"   => 1,
                "created_at"    => date('Y-m-d H:i:s', time())
            ];

            $good_id = Db::table('swt_ty_goods') -> insertGetId($data);
            echo "商品新增成功". $good_id ."\n";
            $path = './storage/app/public/upload/ty_goods/'.$good_id.'/';

            if(!is_dir($path)) {
                mkdir($path, 0777, true);
            }

            $images = Db::table('vms_goods_image') -> where('goods_id', $v -> id) -> get();

            if(empty($images)) {
                continue;
            }

            foreach($images as $image) {
                $fileContent = file_get_contents($image -> image_url);

                if($fileContent) {
                    $fileExtension = pathinfo($image -> image_url, PATHINFO_EXTENSION);

                    $ext = $fileExtension ? : 'jpg';

                    $file_name = Str::random(16).'.'.$ext;

                    $file = $path.$file_name;

                    file_put_contents($file, $data);

                    $file_data = [
                        "ty_goods_id" => $good_id,
                        "url"         => "upload/ty_goods/" . $good_id . "/" . $file_name,
                        "created_at"  => date('Y-m-d H:i:s', time())
                    ];

                    $image_id = Db::table('swt_ty_goods_images') -> insertGetId($file_data);
                    echo "图片新增成功". $image_id ."\n";
                }
            }

        }
    }

    public function resetDelGoods()
    {
        Db::table('swt_goods') -> whereNotNull('deleted_at') -> update(['deleted_at' => null]);
        $this -> info ('已还原删除商品');
    }

    public function delRepeatGoods()
    {
        $arr = Db::table('swt_goods') -> groupBy('bar_code') -> get(Db::raw('MIN(id) as id'));

        $ids = [];

        foreach($arr as $v) {
            $ids[] = $v -> id;
        }

        Db::table('swt_goods')->whereNotIn('id', $ids) -> delete();

        $this -> info ('删除重复商品');
    }

    public function syncBjGoods()
    {
        $num = 0;

        $goods = Db::table('swt_ty_goods') -> get() -> toArray();

        foreach($goods as $good) {
            $num ++;
            $info = Db::table('swt_goods')->where('bar_code', $good->bar_code) -> first();

            if($info) {
                Db::table('swt_goods')->where('id', $info->id) -> update(['source_type' => 0]);
            } else {
                $picture = Db::table('swt_ty_goods_images') -> where('ty_goods_id', $good->id) -> first();

                if($picture) {
                    $url = $picture -> url;
                } else {
                    $url = null;
                }

                $good_data = [
                    'sku_id'      => $good->bar_code,
                    'bar_code'    => $good->bar_code,
                    'goods_name'  => $good->goods_name,
                    'weight'      => $good->weight,
                    'cost_price'  => $good->cost_price,
                    'sell_price'  => $good->sell_price,
                    'goods_picture'     => $url,
                    'source_type' => 0,
                    'created_at' => date('Y-m-d H:i:s',time()),
                    'updated_at' => date('Y-m-d H:i:s',time())
                ];
            }

            $id = Db::table('swt_goods') -> insertGetId($good_data);

            $this->info('新增成功'.$id);
        }

        $this -> info ('商品库合并完成，共计'.$num.'商品');
    }

    public function updateDheGoods()
    {
        $goods_list = Db::table('swt_goods') -> get() -> toArray();

        $num = 0;

        foreach($goods_list as $v) {
            $bar_codes = explode(',', $v -> bar_code);

            foreach($bar_codes as $k => $bar_code)
                if($k == 0) {
                    Db::table('swt_goods') -> where('id', $v->id) -> update(['bar_code' => $bar_code,'sku_id' => $bar_code]);
                } else {
                    $data = [
                        'sku_id'        => $bar_code,
                        'bar_code'      => $bar_code,
                        'goods_name'    => $v->goods_name,
                        'weight'        => $v->weight,
                        'cost_price'    => $v->cost_price,
                        'sell_price'    => $v->sell_price,
                        'goods_picture' => $v->goods_picture,
                        'created_at'    => $v->created_at,
                        'updated_at'    => $v->updated_at,
                        'source_type'   => 1,
                    ];
                    Db::table('swt_goods') -> insert($data);
                }
            $num ++;
        }
        $this -> info ('原商品库构建完成，共计'.$num.'商品');
    }
}
